package com.example.programming.sys.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.programming.sys.entity.HomeworkVo;
import com.example.programming.sys.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import com.example.programming.common.Result;
import com.example.programming.sys.mapper.UserHomeworkMapper;
import com.example.programming.sys.entity.UserHomework;

import com.example.programming.common.tools.BaseController;

import javax.servlet.http.HttpServletResponse;

/**
 * <p>
 *  前端控制器 chrimer
 * </p>
 *
 * @author chrimer
 * @since 2020-08-22
 */
@RestController
@RequestMapping("/sys/userHomework")
public class UserHomeworkController extends BaseController {
    @Autowired
    private UserHomeworkMapper userHomeworkMapper;
    @Autowired
    private UserMapper userMapper;
    @RequestMapping(method= RequestMethod.POST,value="/page")
    public Result page(
        Integer pageNum,
        Integer pageSize) {
        Result result = new Result();
        Page<UserHomework> page = new Page<UserHomework>(pageNum, pageSize);
        UserHomework parms = new UserHomework();
        QueryWrapper<UserHomework> warpper = new QueryWrapper<UserHomework>(parms);

        result.setData(userHomeworkMapper.selectPage(page, warpper));
        return result;
    }
    @RequestMapping(method= RequestMethod.POST,value="/save")
    public Result save(@RequestBody UserHomework entity) {
        Result result = new Result();
        if (entity.getId() == null) {
            userHomeworkMapper.insert(entity);
        } else {
            userHomeworkMapper.updateById(entity);
        }
        return result;
    }
    @RequestMapping(method= RequestMethod.DELETE,value="/delete")
    public Result delete( String ids) {
        Result result = new Result();
        List<String> deleteIds = new ArrayList<String>();
        for (String id : ids.split(",")) {
            deleteIds.add(id);
        }
        userHomeworkMapper.deleteBatchIds(deleteIds);
        return result;
    }

    /**
     * 学生是否提交作业
     * @param id
     * @return
     */
    @GetMapping("isSubmit/{id}")
    public Result isSubmit( @PathVariable("id") String id){
        Result result = new Result();
        UserHomework userHomework = userHomeworkMapper.selectById(id);
        if (StringUtils.isEmpty(userHomework.getUrl())) {
            result.fail("该学生还未提交作业");
            return result;
        }
        return result;
    }
    /**
     * 下载作业
     * @param response
     * @param id
     * @return
     * @throws IOException
     */
    @GetMapping("download/{id}")
    public void download(HttpServletResponse response, @PathVariable("id") String id) throws IOException {
        UserHomework userHomework = userHomeworkMapper.selectById(id);
        String prefix = userHomework.getUrl().substring(userHomework.getUrl().lastIndexOf("."));
        String fileName = userMapper.getnickname(userHomework.getUserId())+prefix;
        FileInputStream inputStream = new FileInputStream(userHomework.getUrl());
            int i = inputStream.available();
        //byte数组用于存放图片字节数据
        byte[] buff = new byte[i];
        inputStream.read(buff);
        //记得关闭输入流
        inputStream.close();
        //设置发送到客户端的响应内容类型
        response.setCharacterEncoding("utf-8");
        response.setContentType("multipart/form-data");
        response.setHeader("content-Disposition",
                "attachment;filename=" + URLEncoder.encode(fileName , "utf-8"));
        response.setHeader("fileName",URLEncoder.encode(fileName , "utf-8"));
        response.setContentType("application/octet-stream");
        OutputStream out = response.getOutputStream();
        out.write(buff);
        //关闭响应输出流
        out.close();
    }

    /**
     * 对作业评分
     * @param homeworkVo
     * @return
     */
    @PostMapping("/score")
    public Result score(@RequestBody HomeworkVo homeworkVo){
        Result result =new Result();
       UserHomework userHomework =  userHomeworkMapper.selectById(homeworkVo.getId());
       userHomework.setScore(homeworkVo.getScore());
       userHomework.setSuggestion(homeworkVo.getSuggestion());
       userHomeworkMapper.updateById(userHomework);
       return result;
    }
}
